package org.singledog.form.builder.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPath;
import org.springframework.util.CollectionUtils;

import java.util.Map;

/**
 * @author adam
 * @date 2020/6/18
 */
public class JsonUtil {

    /**
     * 将target的值合并到source上面，即用target覆盖source
     * @param source
     * @param target
     */
    public static JSONObject mergeJson(JSONObject source, Object target) {
        Map<String, Object> targetPaths = JSONPath.paths(target);
        if (!CollectionUtils.isEmpty(targetPaths)) {
            for (Map.Entry<String, Object> entry : targetPaths.entrySet()) {
                Object val = entry.getValue();
                if (val instanceof JSONObject) {
                    continue;
                }

                if (val instanceof JSONArray) {
                    continue;
                }

                JSONPath.set(source, entry.getKey(), val);
            }
        }

        return source;
    }
}
